/**
 * 任务间使用管道进行输入/输出
 *
 * @author fireway
 * @since 2019年 02月 26日 星期二 07:35:13 CST
 */
package concurrency;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Sender implements Runnable {
    private PipedWriter mPipedWriter = new PipedWriter();
    
    private Random mRandom = new Random(47);
    
    public PipedWriter getPipedWriter() {
        return mPipedWriter;
    }
    
    @Override
    public void run() {
        try {
            while(true) {
                for(char c = 'A'; c <= 'z'; c++) {
                    mPipedWriter.write(c);
                    TimeUnit.MILLISECONDS.sleep(mRandom.nextInt(500));
                }
            }
        } catch(IOException e) {
            System.out.println("Sender write exception: " + e);
        } catch(InterruptedException e) {
            System.out.println("Sender sleep exception: " + e);
        }
    }
}

class Receiver implements Runnable {
    private PipedReader mPipedReader;
    
    public Receiver(Sender sender) {
        try {
            mPipedReader =  new PipedReader(sender.getPipedWriter());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run() {
       try {
           while (true) {
               char c = (char)mPipedReader.read();
               System.out.print("Read: " + c + ", ");
           }
       } catch(IOException e) {
           System.out.println("Receiver read exception: " + e);
       } 
    }
}

public class PipedIO {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);
        exec.execute(sender);
        exec.execute(receiver);
        
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        exec.shutdownNow();
    }
}
